package spitfire.ksim.view;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.text.DateFormat;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import spitfire.ksim.node.KSensor;
import spitfire.ksim.simulator.KSimulator;

/**
 * 
 */
public class KSensorDataPanel extends Plotter2DPanel {
	
	private static final long serialVersionUID = 941369858271904290L;
	private KSimulator simulator;
	private List<Long> timeList;
	private List<Double> dataList;

	public KSensorDataPanel(KSensor sensor, KSimulator simulator) {
		super();
		this.simulator = simulator;
		timeList = sensor.getTimeStampList();
		dataList = sensor.getDataList();
		setData(timeList, dataList);
		if (dataList.size() != 0) {
			setDataWindowBottom(Collections.min(dataList));
			setDataWindowTop(Collections.max(dataList));
		}
		
		setBackground(Color.WHITE);
		setPreferredSize(new Dimension(300, 100));
		setyAxisLoc(2);
		setAxisStatus(Y_AXIS_ONLY);
		setRuler(true);
		setXLabelFormat(DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
				DateFormat.MEDIUM, Locale.GERMANY));
	}

	@Override 
	public void paintComponent(Graphics g) {
 		long simTime = simulator.getSimTime();
 		long timeWindow = simulator.getDynamicTimeWindow();
 		
 		int fromIndex = Collections.binarySearch(timeList, simTime - timeWindow);
		int toIndex = Collections.binarySearch(timeList, simTime);
		if (fromIndex < 0) {
			// not found, convert to insertion point. @see Collections.binarySearch; 
			fromIndex = -fromIndex - 1;
		}
		if (toIndex < 0) {
			toIndex = -toIndex - 1;
		}
		setPlotInterval(fromIndex, toIndex);
		setDataWindowLeft(simTime - timeWindow);
		setDataWindowRight(simTime);
		super.paintComponent(g);
	}
}
